<template>
  <div id="frame" >
    <div id="chat" ref="chatbox">
      <div class="head">
        <h1 align="center" style="width: 100%;padding-top: -20rem"> 聊天室 </h1>
      </div>
      <div class="message-body">
        <Message v-for="message in messages" :key="message.id" :name="message.name" :time="message.time" :content="message.content"
                 :type="message.type"></Message>
      </div>
    </div>




<!--    <div id="danmu-frame" ref="danmuref">-->
<!--      <div style="position: relative;z-index: 10;">-->
<!--        <Danmu v-for="dan in danmus" :key="dan.id" :id="dan.id" :content="dan.content" :color="dan.color" :bold="dan.bold"-->
<!--               :position="dan.position" :size="dan.size" :italic="dan.italic" :width="dan.width" :height="dan.height" :type="dan.type"-->
<!--               @deletedan='deleteDanmu'></Danmu>-->
<!--      </div>-->

<!--        <div style="width: 20%;">-->
<!--          <form action="" style="display: flex;justify-content: space-around;font-size: 25px;">-->
<!--&lt;!&ndash;            <div>&ndash;&gt;-->
<!--&lt;!&ndash;              <span>字体大小：</span>&ndash;&gt;-->
<!--&lt;!&ndash;              <select v-model="message.size">&ndash;&gt;-->
<!--&lt;!&ndash;                <option value="30" checked="checked">小</option>&ndash;&gt;-->
<!--&lt;!&ndash;                <option value="50">中</option>&ndash;&gt;-->
<!--&lt;!&ndash;                <option value="80">大</option>&ndash;&gt;-->
<!--&lt;!&ndash;              </select>&ndash;&gt;-->
<!--&lt;!&ndash;            </div>&ndash;&gt;-->

<!--&lt;!&ndash;            <div>&ndash;&gt;-->
<!--&lt;!&ndash;              <span>字体颜色：</span>&ndash;&gt;-->
<!--&lt;!&ndash;              <select v-model="message.color">&ndash;&gt;-->
<!--&lt;!&ndash;                <option value="#000" checked="checked">黑</option>&ndash;&gt;-->
<!--&lt;!&ndash;                <option value="red">红</option>&ndash;&gt;-->
<!--&lt;!&ndash;                <option value="yellow">黄</option>&ndash;&gt;-->
<!--&lt;!&ndash;                <option value="blue">蓝</option>&ndash;&gt;-->
<!--&lt;!&ndash;                <option value="green">绿</option>&ndash;&gt;-->
<!--&lt;!&ndash;              </select>&ndash;&gt;-->
<!--&lt;!&ndash;            </div>&ndash;&gt;-->

<!--&lt;!&ndash;            <div>&ndash;&gt;-->
<!--&lt;!&ndash;              <span>弹幕位置：</span>&ndash;&gt;-->
<!--&lt;!&ndash;              <select v-model="message.position">&ndash;&gt;-->
<!--&lt;!&ndash;                <option value="0" checked="checked">随机</option>&ndash;&gt;-->
<!--&lt;!&ndash;                <option value="1">顶端</option>&ndash;&gt;-->
<!--&lt;!&ndash;                <option value="2">底部</option>&ndash;&gt;-->
<!--&lt;!&ndash;              </select>&ndash;&gt;-->
<!--&lt;!&ndash;            </div>&ndash;&gt;-->

<!--&lt;!&ndash;            <div>&ndash;&gt;-->
<!--&lt;!&ndash;              <span>加粗：</span>&ndash;&gt;-->
<!--&lt;!&ndash;              <input type="checkbox" v-model="message.bold" />&ndash;&gt;-->
<!--&lt;!&ndash;            </div>&ndash;&gt;-->

<!--&lt;!&ndash;            <div>&ndash;&gt;-->
<!--&lt;!&ndash;              <span>斜体：</span>&ndash;&gt;-->
<!--&lt;!&ndash;              <input type="checkbox" v-model="message.italic" />&ndash;&gt;-->
<!--&lt;!&ndash;            </div>&ndash;&gt;-->








      <!--            <div style="padding-left: 8rem">-->
<!--              <span>昵称：</span>-->
<!--              <input class="form-input" @keyup.enter="send()" v-model="message.name" type="text" maxlength="6" />-->
<!--            </div>-->


<!--            <div>-->
<!--              <span>内容：</span>-->
<!--              <input class="form-input" @keyup.enter="send()" v-model="message.content" type="text" maxlength="140" />-->
<!--            </div>-->


    <div class="m-content" style="margin-top: 2rem" >

      <el-form  label-width="100px"  >
        <el-form-item label="化名" prop="title">
          <el-input  style="width: 6rem" v-model="message.name"></el-input>
        </el-form-item>

        <el-form-item label="内容" prop="description">
          <el-input type="textarea"  style="width: 6rem" v-model="message.content"></el-input>
        </el-form-item>

        <el-form-item style="position: fixed">
          <el-button  @click="back()">返回</el-button>
          <el-button type="primary" @click="send()">发送</el-button>

        </el-form-item>

      </el-form>

    </div>


      </div>


</template>

<script>
var socket;
var time = new Date()
import Message from './Message.vue'
import Danmu from './Danmu.vue'
const uuid = require('uuid')
//websocket服务器的地址  ws://ip:端口/netty_context_path
const ip = "119.29.28.133"      		//后端ip地址
const netty_port = 7000      		//和后端保持一致
const server_port = 8081  			//和后端保持一致
const context_path = "/groupchat"   //和后端保持一致

export default {
  name: "Room",
  components: {
    Message,
    Danmu
  },
  data() {
    return {
      message: {
        'content': "",
        'size': '30',
        'color': '#000',
        'bold': false,
        'italic': false,
        'position': 0,
        'ip': '119.29.28.133',
        'name': "童鞋",
        'time': '',
        'available': 1
      },
      sendnum: 0,
      messages: [],
      danmus: []
    }
  },
  created() {
    this.findall()
    var _self = this
    //判断当前的浏览器是否支持 websocket
    if (window.WebSocket) {
      //go on
      console.log("ws://"+ip+":"+netty_port+context_path);
      socket = new WebSocket("ws://"+ip+":"+netty_port+context_path)

      //相当于channelRead0，ev收到服务器端回送的消息
      socket.onmessage = function(ev) {
        var data = JSON.parse(ev.data)
        _self.addMessage(data, 0)
        // _self.addDanmu(data, 0)
      }
      //相当于连接开启
      socket.onopen = function(ev) {
        console.log("连接开启了...");
        //rt.value = "连接开启了..."
      }

      //感知到连接关闭
      socket.onclose = function(ev) {
        console.log("连接关闭了...");
        // rt.value = rt.value + "\n" + "连接关闭了..."
      }
    } else {
      alert("当前的浏览器不支持websocket");
    }
  },
  methods: {
    findall()
    {

      this.$axios.get("/message/findAll").then(res=>{
        console.log("hi,caonima"+ res.data)
        this.messages=res.data.data
        this.scrollToBottom()
      })
    },
    //消息框滑轮触底
    scrollToBottom() {
      var _self = this
      window.setTimeout(function() {
        _self.$refs.chatbox.scrollTop = 100000000
      }, 100);
    },
    send() {
      var _self = this
      if (socket.readyState == WebSocket.OPEN) {
        this.message.content = this.message.content.replace(/^\s*|\s*$/g,"");  //内容去首尾空格
        this.message.name = this.message.name.replace(/^\s*|\s*$/g,"");    //昵称去首尾空格
        if (this.message.content != '' && this.message.name !='') {
          this.message.time = this.getTime()
          //后端springboot存储弹幕接口地址
          console.log("http://"+ip+":"+server_port+context_path+"/message/save", this.message);
          this.$axios.post("/message/save", this.message).then(res => {
            this.message.content = ""
          });
          this.addMessage(this.message, 1)
          // this.addDanmu(this.message, 1)
          //通过socket 发送消息
          socket.send(JSON.stringify(this.message))
        }
      } else {
        alert("连接没有开启")
      }
    },
    //添加消息
    addMessage(message, type) {
      var msg = new Object();
      msg.id = uuid.v4()
      msg.name = message.name;
      msg.content = message.content
      msg.time = message.time
      msg.type = type
      this.messages.push(msg)
      this.scrollToBottom()
    },
    back()
    {
      this.$router.push('/blogs')
    },
    // //添加弹幕
    // addDanmu(data, type) {
    //   var danmu = new Object();
    //   danmu.id = uuid.v4()
    //   danmu.content = data.content;
    //   danmu.color = data.color;
    //   danmu.position = data.position
    //   danmu.size = data.size
    //   danmu.type = type
    //   // console.log(this.$refs.danmuref)
    //   danmu.width = this.$refs.danmuref.offsetWidth
    //   danmu.height = this.$refs.danmuref.offsetHeight
    //   if (data.bold) danmu.bold = 'bolder'
    //   else danmu.bold = 'normal'
    //   if (data.italic) danmu.italic = 'italic'
    //   else danmu.italic = 'normal'
    //   this.danmus.push(danmu)
    // },
    // //删除弹幕
    // deleteDanmu(ids) {
    //   this.danmus = this.danmus.filter(danmu => danmu.id != ids)
    // },
    //时间格式
    getTime() {
      var t = time.getFullYear() + '-' + (time.getMonth() + 1) + '-' + time.getDate() +
          " " + time.getHours() + ':' + time.getMinutes() + ':' + time.getSeconds();
      return t;
    }

  }


}
</script>
<style scoped>
#frame {
  width: 40%;
  height: 60%;
  margin: 0 auto;
  padding-left: 0.4rem;

  position: absolute;
}

#chat {
  float: left;
  width: 230%;
  height: 110%;
  /*background-image: url(../assets/bg1.jpg);*/
  /*background-repeat: no-repeat;*/
  /*background-size: cover;*/
  background-color: #fafafa;
  opacity: 0.5;
  border-radius: 25px;
  overflow-y: scroll;

}

/*#danmu-frame {*/
/*  float: left;*/
/*  width: 75%;*/
/*  height: 100%;*/
/*  background-color: #FFF;*/
/*  overflow: hidden;*/
/*  background-image: url(../assets/bg2.jpg);*/
/*  background-repeat: no-repeat;*/
/*  background-size: cover;*/
/*}*/

.head {
 width: 9.2rem;
  height: 1.5rem;
  overflow: hidden;
  border-bottom: 2px solid #000000;
  color: black;

}

.head-text {
  position: sticky;
}

.input {
  position: absolute;
  width: 5rem;
  height: auto;
  min-height: 50px;
  bottom: 0;
  background-color: pink;
  overflow: hidden;
  padding: 1%;
  z-index: 20;
}

.form-input {
  /* float: left; */
}

.message-body {
  padding-top: 10%;
}
</style>
